package com.gulimall.search.serivce.impl;

import com.alibaba.fastjson.JSON;
import com.common.constant.search.EsConstant;
import com.common.to.es.SkuEsModel;
import com.gulimall.search.config.ElasticSearchConfig;
import com.gulimall.search.serivce.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author: Ren(任佳宝)
 * @Description: ProductSaveSerivceImpl
 * @Date: 2025/1/18 下午5:58
 * @Version: 1.0
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource

    private RestHighLevelClient restHighLevelClient;


    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        // 给es建立索引、建立映射关系
        // 保存数据
        BulkRequest bulkRequest = new BulkRequest();
        // 批量出入数据
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 执行插入语句
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // 批量错误处理
        boolean b = bulk.hasFailures();
        if (b) {
            Stream<String> failIds = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId);
            log.error("商品商家错误:【{}】", failIds);
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }
}
